package com.lyw.GeoLocationClient.service;

import android.content.Context;
import com.lyw.GeoLocationClient.App;
import com.lyw.GeoLocationClient.utils.SharePreferenceUtil;
import com.lyw.GeoLocationClient.utils.StringUtils;
import com.lyw.GeoLocationClient.json.em.EMResponse;
import com.lyw.GeoLocationClient.json.em.RegUserRequest;
import com.lyw.GeoLocationClient.json.em.TokenRequestBody;
import com.lyw.GeoLocationClient.json.em.TokenResponse;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import timber.log.Timber;

public class EMUserManager {
    private EMUserService emUserService;
    private static String mToken;
    SharePreferenceUtil sp;

    public EMUserManager(Context context) {
        setupApi(context);
        if (App.isAdmin()) {
            setupToken();
        }
    }

    private void setupToken() {
        sp = App.getSpUtil();
        mToken = sp.getToken();
        if (StringUtils.isNullOrEmpty(mToken)) {
            requestToken();
        } else {
            long expiredAt = sp.getEaseExpired();
            if (System.currentTimeMillis() >= (expiredAt - 86400)) {
                requestToken();
            }
        }
    }

    private void requestToken() {
        emUserService.requestToken(new TokenRequestBody(), new Callback<TokenResponse>() {
            @Override
            public void success(TokenResponse tokenResponse, Response response) {
                if (tokenResponse != null) {
                    mToken = tokenResponse.getAccess_token();
                    Timber.d("get Token " + mToken);
                    long expir = System.currentTimeMillis() + tokenResponse.getExpires_in();

                    sp.setToken(mToken);
                    sp.setEaseExpired(expir);
                }
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                mToken = "";
                Timber.e("get token error " + retrofitError.toString());
            }
        });

    }

    private void setupApi(Context context) {
        Timber.d(" setup emu api service !");
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint("https://a1.easemob.com")
                .setErrorHandler(new RetrofitErrorHandler(context))
                .build();
        if (App.DEBUG) {
            restAdapter.setLogLevel(RestAdapter.LogLevel.HEADERS_AND_ARGS);
        }
        emUserService = restAdapter.create(EMUserService.class);
    }

    public EMResponse registerUser(String username, String password) {
        return emUserService.regUser(new RegUserRequest(username, password));
    }

    public void addFriend(String owner, String friend) {
        emUserService.addFriend(getAuto(), owner, friend, new Callback<EMResponse>() {
            @Override
            public void success(EMResponse emResponse, Response response) {

            }

            @Override
            public void failure(RetrofitError retrofitError) {

            }
        });
    }

    public String getAuto() {
        return "Bearer " + mToken;
    }
}
